package umg.gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.StringTokenizer;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import umg.Constants;
import umg.util.PropertyManager;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class ConfigureDialog extends javax.swing.JDialog implements ChangeListener, ActionListener
{

	private static final long serialVersionUID = 4500135061768853496L;
	private JPanel configurePanel;
	private JButton cancelButton;
	private JTextField threadPriorityLabel;
	private JButton closeButton;
	private JTextField refreshLabel;
	private JSlider threadPrioritySlider;
	private JLabel jLabel2;
	private JLabel jLabel3;
	private JButton applySkinButton;
	private JComboBox skinComboBox;
	private JTabbedPane textSettingTabs;
	private JSlider refreshSlider;
	private JLabel jLabel1;
	HashMap<String, String> lfmap;
	private JLabel jLabel4;

	//text areas
	JTextArea autoKickNamesTextArea, ipWatchListTextArea, adminIPSTextArea, nameWatchListTextArea;

	/**
	 * Auto-generated main method to display this JDialog
	 */
	public static void main(String[] args)
	{
		new ConfigureDialog(new JFrame());
	}

	JFrame parentFrame = null;

	public ConfigureDialog(JFrame frame)
	{
		super(frame);
		this.parentFrame = frame;
		initGUI();
	}

	public ConfigureDialog()
	{
		initGUI();
	}

	private void initGUI()
	{
		try
		{
			new PropertyManager();
			//this.setDefaultCloseOperation(HIDE_ON_CLOSE);
			this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);//disable close,
			this.setTitle("Settings");
			configurePanel = new JPanel();
			getContentPane().add(configurePanel, BorderLayout.CENTER);
			configurePanel.setLayout(null);
			configurePanel.setPreferredSize(new java.awt.Dimension(422, 300));
			configurePanel.setSize(414, 272);

			jLabel1 = new JLabel();
			configurePanel.add(jLabel1);
			jLabel1.setText("Refresh Every (Seconds)");
			jLabel1.setBounds(12, 17, 148, 14);

			refreshSlider = new JSlider();
			refreshSlider.addChangeListener(this);
			configurePanel.add(refreshSlider);
			refreshSlider.setBounds(154, 13, 200, 22);
			refreshSlider.setMinimum(15);
			refreshSlider.setMaximum(300);
			refreshSlider.setToolTipText("How often data is to be fetched. 300 is 5 minutes. Normally 60 seconds is fine.");
			refreshSlider.setValue(Integer.parseInt(PropertyManager.getGrab_interval()));

			refreshLabel = new JTextField();
			configurePanel.add(refreshLabel);
			refreshLabel.setBounds(374, 13, 31, 22);
			refreshLabel.setEditable(false);
			refreshLabel.setAutoscrolls(false);
			refreshLabel.setText("60");
			refreshLabel.setHorizontalAlignment(SwingConstants.CENTER);

			closeButton = new JButton();
			configurePanel.add(closeButton);
			closeButton.setText("Save and Close");
			closeButton.setBounds(185, 273, 147, 24);
			{
				jLabel2 = new JLabel();
				configurePanel.add(jLabel2);
				jLabel2.setText("Thread Priority");
				jLabel2.setBounds(12, 46, 133, 14);
			}
			{
				threadPrioritySlider = new JSlider();
				threadPrioritySlider.addChangeListener(this);
				configurePanel.add(threadPrioritySlider);
				threadPrioritySlider.setBounds(154, 42, 200, 22);
				threadPrioritySlider.setMinimum(1);
				threadPrioritySlider.setMaximum(10);
				threadPrioritySlider.setToolTipText("This determins the priority of fetching data compared to other running processes. You rarely need to set it above 7");
				threadPrioritySlider.setValue(PropertyManager.getThreadPriorityInt());
			}
			{
				threadPriorityLabel = new JTextField();
				configurePanel.add(threadPriorityLabel);
				threadPriorityLabel.setEditable(false);
				threadPriorityLabel.setBounds(374, 42, 31, 22);
				threadPriorityLabel.setAutoscrolls(false);
				threadPriorityLabel.setText("5");
				threadPriorityLabel.setHorizontalAlignment(SwingConstants.CENTER);
				threadPriorityLabel.setText(threadPrioritySlider.getValue() + Constants.EMPTY_STR);
			}
			{
				cancelButton = new JButton();
				configurePanel.add(cancelButton);
				cancelButton.setText("Cancel");
				cancelButton.setBounds(90, 273, 84, 24);
			}
			{
				textSettingTabs = new JTabbedPane(JTabbedPane.BOTTOM, JTabbedPane.SCROLL_TAB_LAYOUT);
				configurePanel.add(textSettingTabs);
				textSettingTabs.setBounds(12, 82, 400, 150);
				textSettingTabs.setBackground(new java.awt.Color(255, 255, 255));
				textSettingTabs.setForeground(new java.awt.Color(0, 0, 0));
			}
			{
				//list all the LAFs
				UIManager.LookAndFeelInfo[] plafs = UIManager.getInstalledLookAndFeels();
				if (lfmap == null)
				{
					lfmap = new HashMap<String, String>(10);
					for (int i = 0; i < plafs.length; i++)
					{
						if (PropertyManager.isDebug()) System.out.println("L&F: " + plafs[i].getName() + " Class: " + plafs[i].getClassName());
						lfmap.put(plafs[i].getName(), plafs[i].getClassName());
					}
				}

				ComboBoxModel skinComboBoxModel = new DefaultComboBoxModel(lfmap.keySet().toArray());
				skinComboBox = new JComboBox();
				configurePanel.add(skinComboBox);
				skinComboBox.setModel(skinComboBoxModel);
				skinComboBox.setSelectedItem(UIManager.getLookAndFeel().getName());//current
				skinComboBox.setBounds(106, 240, 206, 21);
			}
			{
				jLabel3 = new JLabel();
				configurePanel.add(jLabel3);
				jLabel3.setText("Application skin");
				jLabel3.setBounds(12, 243, 133, 14);
			}
			{
				applySkinButton = new JButton();
				configurePanel.add(applySkinButton);
				applySkinButton.setText("Apply Skin");
				applySkinButton.setBounds(316, 238, 96, 24);
				applySkinButton.addActionListener(this);
			}
			{
				jLabel4 = new JLabel();
				configurePanel.add(jLabel4);
				jLabel4.setText("Make sure you enter only one value per line below.");
				jLabel4.setBounds(78, 68, 276, 14);
				jLabel4.setFont(new java.awt.Font("Microsoft Sans Serif", 2, 10));
			}
			//add the tabs
			ipWatchListTextArea = new JTextArea(breakCSV(PropertyManager.getIPWatchList()));
			ipWatchListTextArea.setAutoscrolls(true);
			ipWatchListTextArea.setWrapStyleWord(false);
			ipWatchListTextArea.setLineWrap(true);
			JComponent tab1 = makeTextPanel(ipWatchListTextArea);
			textSettingTabs.addTab("IP Watches", null, tab1, "Player IP Addresses that match/contain these will show up in RED");

			nameWatchListTextArea = new JTextArea(breakDelim(PropertyManager.getNameWatchList(), Constants.NAME_LIST_SEPERATOR));
			nameWatchListTextArea.setAutoscrolls(true);
			nameWatchListTextArea.setWrapStyleWord(false);
			nameWatchListTextArea.setLineWrap(true);
			JComponent tab2 = makeTextPanel(nameWatchListTextArea);
			textSettingTabs.addTab("Name Watches", null, tab2, "Player names containing these words will show up in RED");

			adminIPSTextArea = new JTextArea(breakCSV(PropertyManager.getAdminIPAddresses()));
			adminIPSTextArea.setAutoscrolls(true);
			adminIPSTextArea.setWrapStyleWord(false);
			adminIPSTextArea.setLineWrap(true);
			JComponent tab3 = makeTextPanel(adminIPSTextArea);
			textSettingTabs.addTab("Admin IPs", null, tab3, "Admin IP addresses containing these words will show up in GREEN");

			autoKickNamesTextArea = new JTextArea(breakDelim(PropertyManager.getAutoKickPlayerList(), Constants.NAME_LIST_SEPERATOR));
			autoKickNamesTextArea.setAutoscrolls(true);
			autoKickNamesTextArea.setWrapStyleWord(false);
			autoKickNamesTextArea.setLineWrap(true);
			autoKickNamesTextArea.setPreferredSize(new java.awt.Dimension(396, 120));
			JComponent tab4 = makeTextPanel(autoKickNamesTextArea);
			textSettingTabs.addTab("Auto Kick Names", null, tab4, "Player names containing these words will automatically be kicked.");

			closeButton.addActionListener(this);
			cancelButton.addActionListener(this);

			refreshLabel.setText(umg.util.PropertyManager.getGrab_interval());

			setSize(428, 300);
			this.setUndecorated(true);
			this.setResizable(false);
			this.setVisible(true);
			//this.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * break on comma
	 * @param watchList
	 * @return
	 */
	private String breakCSV(String csv)
	{
		StringBuffer str = new StringBuffer();
		StringTokenizer tok = new StringTokenizer(csv, Constants.IP_LIST_SEPERATOR);
		while (tok.hasMoreTokens())
		{
			if (str != null && str.length() > 0)
			{
				str.append(Constants.NEWLINE);
			}
			str.append(tok.nextElement());

		}
		return str.toString();
	}

	private String breakDelim(String text, String delim)
	{
		StringBuffer str = new StringBuffer();
		StringTokenizer tok = new StringTokenizer(text, delim);
		while (tok.hasMoreTokens())
		{
			if (str != null && str.length() > 0)
			{
				str.append(Constants.NEWLINE);
			}
			str.append(tok.nextElement());
		}
		return str.toString();
	}

	public void stateChanged(ChangeEvent e)
	{
		// System.out.println("State Change: "+e.getSource());
		if (e.getSource() == refreshSlider)
		{
			if (refreshLabel != null)
			{
				refreshLabel.setText(refreshSlider.getValue() + Constants.EMPTY_STR);
			}
		}
		if (e.getSource() == threadPrioritySlider)
		{
			if (threadPriorityLabel != null)
			{
				threadPriorityLabel.setText(threadPrioritySlider.getValue() + Constants.EMPTY_STR);
			}
		}
	}

	public void actionPerformed(ActionEvent e)
	{
		if (e.getActionCommand().equals("Save and Close"))
		{
			PropertyManager.setGrab_interval(refreshSlider.getValue() + Constants.EMPTY_STR);
			PropertyManager.setThreadPriority(threadPrioritySlider.getValue() + Constants.EMPTY_STR);
			PropertyManager.setIPWatchList(joinCSV(trimBlock(ipWatchListTextArea.getText())));
			PropertyManager.setNameWatchList(joinDelim(trimBlock(nameWatchListTextArea.getText()), Constants.NAME_LIST_SEPERATOR));
			PropertyManager.setAdminIPAddresses(joinCSV(trimBlock(adminIPSTextArea.getText())));
			PropertyManager.setAutoKickPlayerList(joinDelim(trimBlock(autoKickNamesTextArea.getText()), Constants.NAME_LIST_SEPERATOR));
			PropertyManager.saveToDisk();
			this.setVisible(false);
			this.dispose();
			if (parentFrame != null) parentFrame.repaint();
			//System.exit(0);
		}
		else if (e.getActionCommand().equals("Cancel"))
		{
			this.setVisible(false);
			this.dispose();
			//System.exit(0);
		}
		else if (e.getActionCommand().equals("Apply Skin"))
		{
			//UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
			String selectedSkin = (String) skinComboBox.getSelectedItem();
			//UIManager.setLookAndFeel(lfmap.get(selectedSkin));
			//this.repaint();
			PropertyManager.setSelectedSkin(selectedSkin);
			JOptionPane.showMessageDialog(this, "Please restart to see the changes.", "Skin changed to '" + selectedSkin + "'", JOptionPane.INFORMATION_MESSAGE);
		}
		else
		{
			System.out.println("Unknown action command: " + e.getActionCommand() + " Event=" + e);
		}
	}

	/**
	 * Given a string containing many lines seperated by \n.
	 * Remove the lines that are < 4 chars in length
	 * @param text
	 * @return
	 */
	private String trimBlock(String text)
	{
		StringBuffer trimmedBlock = new StringBuffer();
		StringTokenizer tok = new StringTokenizer(text, Constants.NEWLINE);
		String temp;
		while (tok.hasMoreTokens())
		{
			temp = tok.nextToken();
			if (temp.length() > 3)
			{
				if (trimmedBlock.length() > 0) trimmedBlock.append(Constants.NEWLINE);
				trimmedBlock.append(temp);
			}
		}
		return trimmedBlock.toString();
	}

	private String joinDelim(String text, String delim)
	{
		if (text == null) return Constants.EMPTY_STR;
		return text.replaceAll(Constants.NEWLINE, delim);
	}

	/*
	 * replace newlines by commas
	 *
	 */
	private String joinCSV(String text)
	{
		if (text == null) return Constants.EMPTY_STR;
		return text.replaceAll(Constants.NEWLINE, Constants.IP_LIST_SEPERATOR);
	}

	protected JComponent makeTextPanel(JTextArea textArea)
	{
		JPanel panel = new JPanel(false);
		JScrollPane scrollPane = new JScrollPane(textArea);
		panel.setLayout(new GridLayout(1, 1));
		panel.add(scrollPane);
		scrollPane.setPreferredSize(new java.awt.Dimension(420, 123));
		//scrollPane.setPreferredSize(new java.awt.Dimension(391, 123));
		return panel;
	}

}
